﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.UI;

public class WebCameraManager : MonoBehaviour {

	public string DeviceName;  
	//public Vector2 CameraSize;
	public float CameraFPS;

	//接收返回的图片数据  
	WebCamTexture _webCamera;  
	public GameObject Plane;//作为显示摄像头的面板
	public GameObject FreezePlane;//作为显示摄像头的面板

	public static WebCameraManager instance = null;

	public void setNormalUV()
	{
		Plane.GetComponent<MeshFilter> ().mesh.SetUVs (0, normalUV);
	}
	public void setFixedUV()
	{
		Plane.GetComponent<MeshFilter> ().mesh.SetUVs (0,FixedUV);
	}

	/// <summary>
	/// Gets the web cam texture. [299,299,color32] in rgb
	/// </summary>
	/// <returns>The web cam texture.</returns>
	public WebCamTexture getWebCamTexture()
	{
//		Texture2D tex = new Texture2D(_webCamera.width,_webCamera.height,TextureFormat.RGB24,false);
//		tex.SetPixels32 (_webCamera.GetPixels32());


		//GameObject.Find ("Capture").GetComponent<Image> ().canvasRenderer.SetTexture (_webCamera);


		return _webCamera;
//		{
//			var bytes = tex.EncodeToPNG ();
//			FileStream file = File.Open (TFTest.getDataPath () + "/screen_beforeResize.png", FileMode.Create);
//			var binary = new BinaryWriter (file);
//			binary.Write (bytes);
//			file.Close ();
//		}

		//tex.Resize (299, 299,TextureFormat.RGBA32,false);
		//TextureScale.Bilinear (tex , 299, 299);  




//		float timeBeforeCapture = Time.realtimeSinceStartup;
//		float timeAfterCapture = Time.realtimeSinceStartup;
//		float gap = timeAfterCapture - timeBeforeCapture;
//		Debug.Log (tex.GetPixels32 ().Length.ToString () + "/" + gap.ToString ());
//
////		{
////			var bytes = tex.EncodeToPNG ();
////			FileStream file = File.Open (TFTest.getDataPath () + "/screen.png", FileMode.Create);
////			var binary = new BinaryWriter (file);
////			binary.Write (bytes);
////			file.Close ();
////		}
//
//		return tex;
	}

	List<Vector4> normalUV = new List<Vector4>();
	List<Vector4> FixedUV = new List<Vector4>();

	void Awake()
	{
		StartCoroutine ("InitCameraCor");
		instance = this;

		FreezePlane.SetActive (false);



//		List<Vector4> uvs = new List<Vector4> ();
//		Plane.GetComponent<MeshFilter> ().mesh.GetUVs (0,uvs);
//
//		for (int i = 0; i < uvs.Count; i++) {
//			//print (uvs [i]);
//			normalUV.Add(uvs[i]);
//
//			Vector4 v = uvs [i];
//			v [1] = 1f - v [1];
//
//
//			//v[0]/= ((float)Screen.height / (float)Screen.width);
//
//
// 
//			uvs [i] = v;
//
//			FixedUV.Add (uvs [i]);
//		}
//
//		Plane.GetComponent<MeshFilter> ().mesh.SetUVs (0,uvs);
		//FreezePlane.GetComponent<MeshFilter> ().mesh.SetUVs (0,uvs);
	}



	public void PlayCamera()
	{
		//Plane.GetComponent<MeshRenderer> ().enabled = true;
		Plane.GetComponent<RawImage> ().enabled = true;
		_webCamera.Play();
	}


	public void StopCamera()
	{
		//Plane.GetComponent<MeshRenderer> ().enabled =false;
		Plane.GetComponent<RawImage> ().enabled = false;
		_webCamera.Stop();
	}

	void Update()
	{
//		Plane.transform.localScale = new Vector3 (Screen.height * factor, 1f, Screen.width * factor);
//		FreezePlane.transform.localScale = new Vector3 (Screen.height * factor, 1f, Screen.width * factor);



	}

	float factor = 0.0006f;

	//float factor = 0.00107f;

	[HideInInspector]
	public bool initialized = false;

	/// <summary>  
	/// 初始化摄像头
	/// </summary>  
	public IEnumerator InitCameraCor()  
	{  
		yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);  
		if (Application.HasUserAuthorization(UserAuthorization.WebCam))  
		{  
			WebCamDevice[] devices = WebCamTexture.devices;  
			int deviceID = 0;
			int front = 0;
			if (Application.platform == RuntimePlatform.IPhonePlayer) {
				int length = WebCamTexture.devices.Length;
				if (length <= 0) {
					for (int i = 0; i < length; i++) {
						if (WebCamTexture.devices [i].isFrontFacing) {
							front = i;
						} else {
							deviceID = i;
						}
					}
				}

			}

			if (devices.Length != 0) {
				DeviceName= devices[deviceID].name;  
				Debug.Log (DeviceName);

				_webCamera=new WebCamTexture(DeviceName,(int)(Screen.height), (int)(Screen.width),(int)CameraFPS);


				//Plane.GetComponent<Renderer> ().material.mainTexture=_webCamera;
				Plane.GetComponent<RawImage>().texture = _webCamera;
				//Plane.GetComponent<RawImage>().canvasRenderer.SetTexture(_webCamera);
				//Plane.transform.localScale = new Vector3 (1,1,1);

				_webCamera.Play();  

				initialized = true;
			}



		}  
	}
}
